/*
 * SDL.cpp
 *
 *  Created on: 23/10/2013
 *      Author: fernando
 */

#include "SDL.h"
#include <iostream>

using std::cout;
using std::endl;

SDL::SDL(unsigned int width, unsigned int heigth) {
	ancho = width;
	alto = heigth;
}

SDL::SDL(){
	ancho = SCREEN_WIDTH;
	alto = SCREEN_HEIGHT;
}

SDL::~SDL() {
	SDL_Quit();
}



SDL_Surface* SDL::load_image(std::string filename){
    //Temporary storage for the image that's loaded
    SDL_Surface* loadedImage = NULL;
    //The optimized image that will be used
    SDL_Surface* optimizedImage = NULL;
    //Load the image
    loadedImage = IMG_Load(filename.c_str());
    //If nothing went wrong in loading the image
	if(loadedImage != NULL){
		//Create an optimized image
		optimizedImage = SDL_DisplayFormat(loadedImage);
		//If the image was optimized just fine
		if(optimizedImage != NULL){
			//Map the color key
			Uint32 colorkey = SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF );
			//Set all pixels of color R 0, G 0xFF, B 0xFF to be transparent
			SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorkey );
		}
		//Free the old image
		SDL_FreeSurface(loadedImage);
	}else{
		cout << "Error al cargar la imagen: " << filename << endl;
	}
	//Return the optimized image
	return optimizedImage;
}

void SDL::apply_surface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip=NULL){
    //Holds offsets
    SDL_Rect offset;
    //Get offsets
    offset.x = x;
    offset.y = y;
    //Blit
    SDL_BlitSurface(source, clip, destination, &offset);
}

void SDL::clean_up(SDL_Surface *image){
    //Free the image
    SDL_FreeSurface(image);
    //Quit SDL
    SDL_Quit();
}


bool SDL::init(std::string caption){
    //Initialize all SDL subsystems
    if(SDL_Init(SDL_INIT_EVERYTHING) == -1){
        return false;
    }
    //Set up the screen
    screen = SDL_SetVideoMode(ancho, alto, SCREEN_BPP, SDL_SWSURFACE);
    //If there was an error in setting up the screen
    if(screen == NULL){
        return false;
    }
    //Set the window caption
    SDL_WM_SetCaption(caption.c_str(), NULL);
     //If everything initialized fine
    return true;
}

SDL_Surface* SDL::getScreen(){
	return screen;
}

